<template>
  <div v-if="editOpen" style="width: 100%;">
      <t-dialog
        :header="header"
        :visible.sync="visible"
        :onClose="onClose"
        width="80%"
        top="5%"
      >
       <div style="height: 65vh">
         <div v-if="rowIndex==null">
           <t-alert style="margin-bottom: 20px" theme="info"
                    :message="`当前页面可重复添加。目前已添加数量: ${data.length} `"/>
         </div>
         <t-form ref="form" resetType="initial"  :data="formData" labelWidth="140px" :rules="rules">
           <t-form-item label="年度：" name="year">
             <t-date-picker style="width: 390px" mode="year" clearable v-model="formData.year"></t-date-picker>
           </t-form-item>
           <t-form-item label="直接经济效益：" name="zjEconomicBenefit">
             <t-input-adornment append="万元">
               <t-input-number :decimal-places="2"
                               @keyup="()=>{if(formData.zjEconomicBenefit){formData.zjEconomicBenefit=Number((formData.zjEconomicBenefit || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                               :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                               v-model="formData.zjEconomicBenefit"
                               theme="normal"
                               :min="0"></t-input-number>
             </t-input-adornment>
           </t-form-item>
           <t-form-item label="间接经济效益：" name="jjEconomicBenefit">
             <t-input-adornment append="万元">
               <t-input-number :decimal-places="2"
                               @keyup="()=>{if(formData.jjEconomicBenefit){formData.jjEconomicBenefit=Number((formData.jjEconomicBenefit || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                               :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                               v-model="formData.jjEconomicBenefit"
                               theme="normal"
                               :min="0"></t-input-number>
             </t-input-adornment>
           </t-form-item>
           <t-form-item label="社会效益概述：" name="socialBenefitContent">
             <t-textarea :autosize="{minRows: 5}"
                         v-model="formData.socialBenefitContent"  placeholder="请输入内容"/>
<!--             <tiny-mce-editor key="socialBenefitContent" v-model="formData.socialBenefitContent"></tiny-mce-editor>-->
           </t-form-item>
           <t-form-item label="经济效益概述：" name="economicBenefitContent">
             <t-textarea :autosize="{minRows: 5}"
                         v-model="formData.economicBenefitContent"  placeholder="请输入内容"/>
<!--             <tiny-mce-editor key="economicBenefitContent" v-model="formData.economicBenefitContent"></tiny-mce-editor>-->
           </t-form-item>
         </t-form>
       </div>
        <template #footer>
          <t-button theme="default" @click="onClose">取消</t-button>
          <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
          <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
        </template>
      </t-dialog>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                 @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data" :columns="columns">
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #zjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
          <template #jjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
<!--          <template #socialBenefitContent="{row}">-->
<!--            <div v-html="row.socialBenefitContent"></div>-->
<!--          </template>-->
<!--          <template #economicBenefitContent="{row}">-->
<!--            <div v-html="row.economicBenefitContent"></div>-->
<!--          </template>-->
        </t-table>
        <div style="margin-top: 10px" class="btn-group-inline">
          <t-button @click="header='新增年度社会、经济效益';rowIndex=null;dialogOpen=true;visible=true">新增
          </t-button>
          <t-button @click="upData">上移</t-button>
          <t-button @click="downData">下移</t-button>
          <t-button @click="updateData">修改</t-button>
          <t-button @click="delData">删除</t-button>
        </div>
      </t-col>
    </t-row>
  </div>
  <div v-else style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-table :loading="dataLoading" size="small" rowKey="id" :data="data" :columns="columns2">
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #zjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
          <template #jjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
<!--          <template #socialBenefitContent="{row}">-->
<!--            <div v-html="row.socialBenefitContent"></div>-->
<!--          </template>-->
<!--          <template #economicBenefitContent="{row}">-->
<!--            <div v-html="row.economicBenefitContent"></div>-->
<!--          </template>-->
        </t-table>
      </t-col>
    </t-row>
  </div>
</template>

<script>
// import TinyMceEditor from "@/components/TinyMceEditor/index.vue";

export default {
  name: "copyright-benefit",
  components: {
    // TinyMceEditor
  },
  props: {
    value: Array,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      rowIndex: null,
      formData:{
        year: '',
        zjEconomicBenefit: null,
        jjEconomicBenefit: null,
        socialBenefitContent: '',
        economicBenefitContent: '',
      },
      rules: {
        year: [
          {
            required: true,
            message: "年度不能为空",
          }
        ],
        zjEconomicBenefit: [
          {
            required: true,
            message: "直接经济效益不能为空",
          }
        ],
        jjEconomicBenefit: [
          {
            required: true,
            message: "直接经济效益不能为空",
          }
        ],
      },
      dialogOpen: false,
      header: "添加",
      visible: false,
      companyLoading: false,
      companyOptions: [],
      dataLoading: false,
      deptMenuOptions: [],
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "year",
          title: "年度",
          align: "center",
          width: 100
        },
        {
          colKey: "zjEconomicBenefit",
          title: "直接经济效益",
          align: "center",
          width: 120
        },
        {
          colKey: "jjEconomicBenefit",
          title: "间接经济效益",
          align: "center",
          width: 120
        },
        {
          colKey: "socialBenefitContent",
          title: "社会效益概述",
          align: "center",
        },
        {
          colKey: "economicBenefitContent",
          title: "经济效益概述",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "year",
          title: "年度",
          align: "center",
        },
        {
          colKey: "zjEconomicBenefit",
          title: "直接经济效益",
          align: "center",
        },
        {
          colKey: "jjEconomicBenefit",
          title: "间接经济效益",
          align: "center",
        },
        {
          colKey: "socialBenefitContent",
          title: "社会效益概述",
          align: "center",
        },
        {
          colKey: "economicBenefitContent",
          title: "经济效益概述",
          align: "center",
        },
      ],
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getCompanyList(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
  },
  created() {
  },
  methods: {
    onSubmit(type){
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.rowIndex !== null) {
            this.$set(this.data, this.rowIndex, {
              softId: this.objId,
              ...this.formData,
            })
            this.$message.success("修改成功");
            this.$refs.form.reset();
            this.dialogOpen = false;
            this.visible = false;
            this.rowIndex = null;
          } else {
            const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
            this.data.push({
              ...this.formData,
              id: newId,
              softId: this.objId,
            })
          }
          this.$refs.form.reset();
          if (type === 1) {
            this.onClose()
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onClose() {
      this.$refs.form.reset();
      this.visible = false;
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (!val.company) {
          this.$set(this.data[index], 'companyStatus', 'error')
          this.$message.error(`专利权人：第${index + 1}条"单位名称"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'companyStatus', 'default')
        return true;
      });
      return isValidate;
    },
    getCompanyList() {
      if (this.objId) {
        this.dataLoading = true;
        this.$api.cgzh.copyright.benefitListGet(this.objId).then(response => {
          this.data = response.data;
          this.dataLoading = false;
        }).catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });
      }
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    addData() {
      this.data.push({
        id: Date.parse(new Date()),
        softId: this.objId,
        year: '',
        socialBenefitContent: '',
        economicBenefitContent: '',
        zjEconomicBenefit: '',
        jjEconomicBenefit: '',
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    updateData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      Object.assign(this.formData, this.data[index])
      this.rowIndex = index;
      this.header = "修改年度社会、经济效益"
      this.dialogOpen = true;
      this.visible = true;
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1);
      this.selectedRowKeys = [];
    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}
.t-form__item {
  margin-bottom: var(--td-comp-margin-xxl);
}
.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
